<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button style="margin-left: 10px" :loading="listLoading" class="filter-item" type="primary"
                 @click="getList">刷新
      </el-button>
    </div>
    <div class="remote-list">
      <template v-for="(rtcStream,index) in rtcStreamList">
        <div class="remote-item" :key="index">
          <video :srcObject.prop="rtcStream" autoplay muted controls></video>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
  import {getStreamPath, getWebRtcRemoteSdp} from "../../api/api";
  import _ from 'lodash';

  export default {
    name: "Home",
    rtcPeerConnection: null,
    data() {
      return {
        iceConnectionState: '',
        rtcPeerConnectionInit: false,
        rtcStreamList: [],
        arrayStr: '',
        listLoading: false
      }
    },
    components: {},
    created() {

    },
    async mounted() {
      await this.getList()
    },
    methods: {
      async getList() {
        this.listLoading = true;
        let response = await getStreamPath();
        let array = response.data || [];
        this.listLoading = false;
        if (array.length > 0) {
          const arrayStr = array.join(',');
          if (arrayStr !== this.arrayStr) {
            this.close();
            console.log('closed');
            await this.initRtcPeerConnection(array.length);
            console.log('initRtcPeerConnectioned');
            try {
              await this.play(arrayStr);
              console.log('played');
            } catch (e) {
              console.error(e);
            }
            this.arrayStr = arrayStr;
          }
        }
      },
      async initRtcPeerConnection(streamLength) {
        const rtcPeerConnection = new RTCPeerConnection();

        console.log('addTransceiver,size', streamLength);
        for (let i = 0; i < streamLength; i++) {
          rtcPeerConnection.addTransceiver('video', {
            direction: "recvonly"
          });
        }

        rtcPeerConnection.onsignalingstatechange = e => {
          console.log('onsignalingstatechange', e);
        };

        rtcPeerConnection.oniceconnectionstatechange = e => {
          console.log('oniceconnectionstatechange', rtcPeerConnection.iceConnectionState);
        };

        rtcPeerConnection.onicecandidate = event => {
          console.log('onicecandidate', event);
        };

        rtcPeerConnection.ontrack = event => {
          console.log('ontrack', event);
          if (event.track.kind === "video") {
            let rtcStream = event.streams[0];
            if (rtcStream) {
              this.rtcStreamList.push(rtcStream);
            }
          }
        };

        rtcPeerConnection.onnegotiationneeded = event => {

        }

        try {
          const rtcSessionDescriptionInit = await rtcPeerConnection.createOffer();
          await rtcPeerConnection.setLocalDescription(rtcSessionDescriptionInit);
        } catch (e) {
          console.warn(e);
        }

        this.rtcPeerConnectionInit = true;
        this.$options.rtcPeerConnection = rtcPeerConnection;
      },
      //
      async play(streamPath) {
        const rtcPeerConnection = this.$options.rtcPeerConnection;
        if (rtcPeerConnection) {
          const localDescriptionData = rtcPeerConnection.localDescription.toJSON();
          try {
            const result = await getWebRtcRemoteSdp(streamPath, localDescriptionData);
            await rtcPeerConnection.setRemoteDescription(new RTCSessionDescription({
              type: result.type,
              sdp: result.sdp
            }));
          } catch (e) {
            console.error(e);
          }
        }
      },
      close() {
        const rtcPeerConnection = this.$options.rtcPeerConnection;
        if (rtcPeerConnection) {
          rtcPeerConnection && rtcPeerConnection.close();
          this.$options.rtcPeerConnection = null;
        }
      }
    },
    destroyed() {
      this.close();
    }
  }
</script>

<style lang="scss" scoped>

  .remote-list {
    display: flex;
    flex-wrap: wrap;
  }

  .remote-item {
    width: 400px;
    height: 400px;
    margin-left: 20px;

    &:first-child {
      margin-left: 0;
    }


    video {
      height: 100%;
      width: 100%;
    }
  }
</style>
